<?php

class Mcart extends MY_Model{
    function add($uid, $pid, $quantity){
        $res = $this->db->query("select * from cart where user_id = $uid and product_id = $pid")->result();
        if (count($res)==0){
            $this->db->query("insert into cart(user_id,product_id,quantity) values($uid,$pid,$quantity)");
        }
        else  $this->db->query("update cart set quantity = $quantity where user_id = $uid and product_id = $pid");
    }
    function remove($uid,$pid){
        $this->db->query("delete from cart where user_id = $uid and product_id = $pid");
    }
    function get($uid){
        return $this->db->query("select tbl3.product_id, tbl3.product_name, tbl3.description, tbl3.url_image, tbl3.product_category_id, tbl3.quantity_remaining, quantity, round(if(new_price is null, tbl3.unit_price, new_price),2) as unit_price from (select product.*, cart.quantity from cart, product where user_id = $uid and cart.product_id = product.product_id ) tbl3 left join (select tb1.*, new_price from product tb1 left join (select product.product_id, round((1- promotion.discount)*product.unit_price,2) as new_price from promotion_detail, promotion, product where promotion.promotion_id in (select promotion_id from promotion where start_date <= now() and end_date>= now()) and promotion.promotion_id = promotion_detail.promotion_id and promotion_detail.product_id = product.product_id) tb2 on tb1.product_id = tb2.product_id) tbl4 on tbl3.product_id = tbl4.product_id")->result();
    }

}